import React, { Component, useRef, useState, useEffect } from 'react';
import {StatusBar,View,LayoutAnimation,ScrollView,Linking,Text,TouchableOpacity } from 'react-native';
import {widthPercentageToDP as wp, heightPercentageToDP as hp} from 'react-native-responsive-screen';

let diagramData = undefined;

/**
 * 
 * 1-30M しおかぜ
 * 31-58D 南風
 * 1001-1030M いしづち(併結)
 * 1041-1046M いしづち(単独)
 * 1051-1082D 宇和海
 * 1091M MX松山
 * 1092M MX高松
 * 2001-2010D しまんと
 * 2071-2086D あしずり
 * 3001-3033D うずしお
 * 3101-3177M マリンライナー
 * 4001-4011D 剣山
 * 5006,13,22,29 うずしお(岡山直通南風併結)
 * 5831-5843D 土佐くろしお鉄道ごめん・なはり線直通快速
 * 5853-5892D 土佐くろしお鉄道ごめん・なはり線直通普通
 * 8011,8012D 四国まんなか千年ものがたり
 * 8031,(8041) サンライズ瀬戸, 琴平(延長)
 * 8053,8054D トキの夜明けのものがたり
 * 8176,8179D アンパントロッコタカマツ
 * 8277,8278D アンパントロッココトヒラ
 * 8451,8452D よしの川トロッコ
 * 8814,8819D しまんトロッコ
 * 8911-8914D 伊予灘ものがたり
 * 9001-9030* いしづち(リレー)
 * 9031M サンライズ瀬戸琴平(延長)(臨時？)
 * 9062D 四国まんなか千年ものがたり(臨時？)
 */
export default function LED_vision(props){
    const HeaderConfig = {
        headers:{
          'referer': 'https://train.jr-shikoku.co.jp/sp.html'
        }
    }
    const [trainDiagram,setTrainDiagram] = useState(null);
    const [stationDiagram,setStationDiagram] = useState(null);
    const [currentTrain, setCurrentTrain] = useState(null);
    useEffect(()=>{
        fetch('https://train.jr-shikoku.co.jp/g?arg1=station&arg2=traintimeinfo&arg3=dia', HeaderConfig).then(response => response.text()).then(d=>{
            const val = d.replace("[\r\n","").split(',\r\n');
            let returnData = {};
            val.forEach(element =>{
                try{
                    let data = JSON.parse(element);
                    Object.keys(data).forEach( key => returnData[key] = data[key] );
                }catch(e){
                }
            })
            return(returnData);
        }).then((trainDiagram)=>{
            let returnData = {};
            if(trainDiagram){
                Object.keys(trainDiagram).forEach( key => {
                
                    if(trainDiagram[key].match(props.stationName.今.name) ){
                        returnData[key] = trainDiagram[key];
                    }
                });    
            }
            setTrainDiagram(trainDiagram);
            setStationDiagram(returnData);

        })
    },[]);
    const getTime = ()=>{
        const returnData = [];
        const date = new Date();
        Object.keys(stationDiagram).forEach((d)=>{
            let a = (() =>{
                let returnData = {};
                stationDiagram[d].split("#").forEach((data)=>{
                    if(data.match("着")){
                        returnData.lastStation = data.split(",着,")[0];
                    }
                    if(data.match(props.stationName.今.name)){
                        if(data.match(",発,")){
                            returnData.time = data.split(",発,")[1];
                        }
                        else{
                            returnData.time = data.split(",着,")[1];
                            returnData.lastStation = "当駅止"
                        }
                        
                    }
                })
                return returnData;
            })();
            returnData.push({train:d,time:a.time,lastStation:a.lastStation});
        })
        
        return (returnData.sort((a,b)=> {
            if(parseInt(a.time.split(":")[0]) < parseInt(b.time.split(":")[0])){
                return -1;
            }
            else if(parseInt(a.time.split(":")[0]) > parseInt(b.time.split(":")[0])){
                return 1;
            }
            else if(parseInt(a.time.split(":")[1]) < parseInt(b.time.split(":")[1])){
                return -1;
            }
            else if(parseInt(a.time.split(":")[1]) > parseInt(b.time.split(":")[1])){
                return 1;
            }
        }))

    };
    const trainTimeAndNumber = stationDiagram != null ? getTime() : null;
    useEffect(()=>{
        fetch("https://train.jr-shikoku.co.jp/g?arg1=train&arg2=train", HeaderConfig).then(response => response.json()).then(d=>d.map(x=>({num:x.TrainNum,delay:x.delay}))).then(d=>{
            setCurrentTrain(d)});
    },[])
    
    const filtering = d =>  currentTrain.map(m=>m.num).includes(d.train)
    
    return(
        <View style={{ width: wp("98%"),/*  height: wp("98%")/10*9, */backgroundColor:"#432",borderWidth:1,margin:10,marginHorizontal:wp("1%")}} >
            <View style={{alignContent:"center",alignItems:"center",width:"100%",marginVertical:10}}>
                <Text style={{fontSize:parseInt("25%"),color:"white",fontWeight:"bold"}}>次の列車</Text>
                <Text style={{fontSize:parseInt("15%"),color:"white"}}>Next Train</Text>
            </View>
            {trainTimeAndNumber ? currentTrain && trainTimeAndNumber.filter(filtering).map((d,index)=>
            <View style={{alignContent:"center",alignItems:"center",width:"94%",marginVertical:5,marginHorizontal:"3%",backgroundColor:"#000",flexDirection:"row"}}>
                <View style={{flex:6,flexDirection:"row"}}>
                    {/* <Text style={{fontSize:parseInt("25%"),color:"red",fontWeight:"bold"}}>検証中</Text> */}
                    <Text style={{fontSize:parseInt("22%"),color:"white",fontWeight:"bold"}}>{d.lastStation}</Text>
                </View>
                <View style={{flex:3}}>
                    <Text style={{fontSize:parseInt("22%"),color:"white",fontWeight:"bold"}}>{d.time}</Text>
                </View>
                <View style={{flex:4}}>
                    <Text style={{fontSize:parseInt("22%"),color:"white",fontWeight:"bold"}}>{d.train}</Text>
                </View>
                <View style={{flex:5}}>
                    <Text style={{fontSize:parseInt("22%"),color:"white",fontWeight:"bold"}}>{(()=>{
                        let data= currentTrain.filter(data=>data.num==d.train)[0].delay;
                        if(isNaN(data)){
                            return data;
                        }
                        else if(data == 0){
                            return "定刻通り"
                        }
                        else{
                            return data+"分遅れ"
                        }
                        })()}</Text>
                </View>
            </View>
            )
            : null}
            
          </View>
    )
}
