/* eslint-disable prettier/prettier */
/* eslint-disable react-native/no-inline-styles */
/* eslint-disable prettier/prettier */
/* eslint-disable prettier/prettier */
import React from 'react';
import {
  ImageBackground,
  Text,
  View,
  StatusBar,
  TouchableHighlight,
  Button,
  Modal,
  TouchableOpacity,
  Dimensions,
  BackHandler,
  ScrollView,
  Image,
} from 'react-native';
import styles from '../style/styleListen';
import {Stopwatch} from 'react-native-stopwatch-timer';
import Orientation from 'react-native-orientation';
import * as RNFS from 'react-native-fs';
import Listennotes from './dataListen';
import octavelist from './dataOctave';
//import OtherClass from './saveRecords';
import Sound from 'react-native-sound';
import moment from 'moment';
import AsyncStorage from '@react-native-async-storage/async-storage';
const path1 = RNFS.DocumentDirectoryPath + '/counterlisten.txt';

const config = {
  deviceWidth: Dimensions.get('window').height,
  deviceHeight: Dimensions.get('window').width,
};
const date = moment().utcOffset('+08:00').format('D MMM');
const time = moment().utcOffset('+08:00').format('h:mm a');
const day = moment().utcOffset('+08:00').format('ddd');

const NOTESWHITE = [{name: 'A0'},{name: 'B0'},
  {name: 'C1'},{name: 'D1'},{name: 'E1'},{name: 'F1'},{name: 'G1'},{name: 'A1'},{name: 'B1'},
  {name: 'C2'},{name: 'D2'},{name: 'E2'},{name: 'F2'},{name: 'G2'},{name: 'A2'},{name: 'B2'},
  {name: 'C3'},{name: 'D3'},{name: 'E3'},{name: 'F3'},{name: 'G3'},{name: 'A3'},{name: 'B3'},
  {name: 'C4'},{name: 'D4'},{name: 'E4'},{name: 'F4'},{name: 'G4'},{name: 'A4'},{name: 'B4'},
  {name: 'C5'},{name: 'D5'},{name: 'E5'},{name: 'F5'},{name: 'G5'},{name: 'A5'},{name: 'B5'},
  {name: 'C6'},{name: 'D6'},{name: 'E6'},{name: 'F6'},{name: 'G6'},{name: 'A6'},{name: 'B6'},
  {name: 'C7'},{name: 'D7'},{name: 'E7'},{name: 'F7'},{name: 'G7'},{name: 'A7'},{name: 'B7'},
  {name: 'C8'},
];

const NOTESBLACK = [{name: 'A#0', left: 0.046},
  {name: 'C#1',left: 0.195},{name: 'D#1',left: 0.27},{name: 'F#1',left: 0.42},{name: 'G#1',left: 0.496},{name: 'A#1',left: 0.57},
  {name: 'C#2',left: 0.72},{name: 'D#2',left: 0.795},{name: 'F#2',left: 0.945},{name: 'G#2',left: 1.02},{name: 'A#2',left: 1.095},
  {name: 'C#3',left: 1.245},{name: 'D#3',left: 1.32},{name: 'F#3',left: 1.47},{name: 'G#3',left: 1.545},{name: 'A#3',left: 1.62},
  {name: 'C#4',left: 1.77},{name: 'D#4',left: 1.845},{name: 'F#4',left: 1.995},{name: 'G#4',left: 2.07},{name: 'A#4',left: 2.145},
  {name: 'C#5',left: 2.295},{name: 'D#5',left: 2.37},{name: 'F#5',left: 2.52},{name: 'G#5',left: 2.595},{name: 'A#5',left: 2.67},
  {name: 'C#6',left: 2.82},{name: 'D#6',left: 2.899},{name: 'F#6',left: 3.045},{name: 'G#6',left: 3.12},{name: 'A#6',left: 3.197},
  {name: 'C#7',left: 3.345},{name: 'D#7',left: 3.42},{name: 'F#7',left: 3.57},{name: 'G#7',left: 3.645},{name: 'A#7',left: 3.72},
];

const keywordsList = [];
const corSound = require('../media/sound/correct.mp3');
const wroSound = require('../media/sound/wrong.mp3');
const keySound = Listennotes;

var soundN = '';
var indexS = 0;
var stime = 0;
var imageN = '';
var indexN = 0;

class Listen extends React.Component {
    constructor(props) {
    super(props);
    Sound.setCategory('Playback'); // true = mixWithOthers
    this.state = {
      logbook: [],
      index:0,
      correct: 0,
      wrong: 0,
      keywordsList: '',
      count: 1,
      name : '',
      start : true,
      showC : false,
      showW : false,
      showDone : false,
      showQuit : false,
      showMusic : false,
      maxCount : 5,
      records: [],
      choose :  octavelist,
      soundName : '',
      keynumber: 0,
    };
  }

    toggleKeyword = (keyword) => {
    console.log('Press: ' + keyword);
    //indexS = Listennotes.findIndex(item=> item.name === keyword);
    console.log(Listennotes[indexS].name);
     if (this.state.keynumber === 0) {
        this.playButton();
        this.setState({keynumber : this.state.keynumber + 1});
     }
     if (this.state.keynumber === 1) {
       this.answer(keyword);
       this.setState({keynumber : 0});
     }
  };

  answer = (keyword) => {
     if (keyword === Listennotes[indexS].name) {
         this.correctAlert();
      if ( (this.state.count + 1) > this.state.maxCount) {
        this.setState({correct : this.state.correct + 1});
        this.setState({showDone: true});
        this.listenRecord(this.state.correct, (this.state.wrong + 1), stime);
        //console.log('finish');
      }
      else {
        this.setState({correct : this.state.correct + 1, count:this.state.count + 1, showC: true});
            this.displayData1();
    }
    } else {
       this.wrongAlert();
      if ( (this.state.count + 1) > this.state.maxCount) {
        this.setState({wrong : this.state.wrong + 1});
        this.setState({showDone: true});
        this.listenRecord(this.state.correct, (this.state.wrong + 1), stime);
        //console.log('finish');
      }
      else {
        this.setState({showW: true});
        this.setState({wrong : this.state.wrong + 1, count:this.state.count + 1});
         this.displayData1();
    }
    }
  };

     listenRecord = async(correct, wrong, timer) => {
     var listR = [];
      let obj = {
      correct: correct,
      wrong: wrong,
      timer: timer,
      date: date,
      time: time,
      day : day,
    };
       this.setState({records : obj});
        try {
        var value = await AsyncStorage.getItem('@listening_key');
        if (value !== null) {
            value = JSON.parse(value);
            value.push(obj);
            //  console.log(value);
            // console.log('We have data!!');
              AsyncStorage.setItem('@listening_key', JSON.stringify(value), (err)=> {
              if (err){
                  console.log('an error');
                  throw err;
              }
        // console.log('success');
          }).catch((err)=> {
              console.log('error is: ' + err);
          });
        }
        else {
          listR.push(obj);
            AsyncStorage.setItem('@listening_key', JSON.stringify(listR), (err)=> {
              if (err){
                  console.log('an error');
                  throw err;
              }
        // console.log('success');  //console.log(JSON.stringify(this.state.listN));
          }).catch((err)=> {
              console.log('error is: ' + err);
          });
        }
    } catch (error) {
        // Error retrieving data
    }
      };


  homeExit = async () => {
   this.setState({showQuit: true});
  };


  playButton = () => {
   //console.log('play');
    indexS = Listennotes.findIndex(item=> item.name ===  this.state.soundName);
    //console.log(indexS);
    console.log('Play Sound:' + Listennotes[indexS].name);
    this.setState({showMusic: true});
    var playSound = new Sound(keySound[indexS].url, (error) => {
      if (error) {
        console.log('failed to load the sound', error);
        return;
      }
      // loaded successfully
      playSound.play((success) => {
        if (success) {
         // console.log('successfully finished playing');
          this.setState({showMusic: false});
        } else {
         // console.log('playback failed due to audio decoding errors');
          playSound.release();
        }
      });
    });

  };

 reset = () => {
   this.setState({count:1});
  };

   backAction = () => {
   this.setState({showDone: false, showQuit: false});
   this.props.navigation.navigate('1');
   Orientation.lockToPortrait();
  };

  correctAlert = () => {
     var corrSound = new Sound(corSound, (error) => {
      if (error) {
        console.log('failed to load the sound', error);
        return;
      }
      // loaded successfully
      corrSound.play((success) => {
        if (success) {
         // console.log('successfully finished playing');
        } else {
         // console.log('playback failed due to audio decoding errors');
          corrSound.release();
        }
      });
    });
  };

  wrongAlert = () => {
     var wrongSound = new Sound(wroSound, (error) => {
      if (error) {
        console.log('failed to load the sound', error);
        return;
      }
      // loaded successfully
      wrongSound.play((success) => {
        if (success) {
         // console.log('successfully finished playing');
        } else {
         // console.log('playback failed due to audio decoding errors');
          wrongSound.release();
        }
      });
    });
  };


  componentDidMount() {
  //this.removeArray();
  BackHandler.addEventListener('hardwareBackPress', this.homeExit);
  Orientation.lockToLandscape();
  //this.randomSound();
  this.displayData1();
  this.reset();
  }

    componentWillUnmount() {
       //this.removeArray();
     BackHandler.removeEventListener('hardwareBackPress', this.homeExit);
    //clearInterval(this.interval);
   // Orientation.lockToLandscape();
  }
  ';';

   randomSound(){
            // console.log(ccc);
            //  soundN = Math.floor(Math.random() * keySound.length);
            //  console.log(Listennotes[soundN]);
              //indexS = Listennotes.findIndex(item=> item.name === this.state.name);
           console.log(this.state.name);
           //   console.log(indexN);
            console.log(this.state.records);
              soundN = Math.floor(Math.random() * this.state.records.length);
            //  console.log(soundN);
               this.setState({
                soundName : this.state.records[soundN].name,
                });
              console.log('Random Sound:' + this.state.soundName);
      }


 /* displayData = async () => {
  try {
    const value = await AsyncStorage.getItem('@listen_key');
    console.log(JSON.parse(value));
    console.log(octave.map((octaven) => octaven.nameoctave));
    console.log(octave.map((octaven) => octaven.listoctave.map((n) => n.name)));
  } catch (error) {
    // Error retrieving data
  }
};
*/

  displayData1 = async () => {
// this.setState({records: []});
  try {
    const value = await AsyncStorage.getItem('@listen_key');
   /// console.log(JSON.parse(value));
    if (value !== null) {
      // We have data!!
       this.setState({
          logbook: JSON.parse(value),
        });
        // console.log(this.state.logbook);
      RNFS.readFile(path1, 'ascii')
        .then((ccc) => {
        console.log('has notes has counter');
       // console.log(ccc);
        imageN = Math.floor(Math.random() * this.state.logbook.length);
        this.setState({
        name : this.state.logbook[imageN],
        maxCount : ccc,
        records : octavelist[imageN].listoctave,
        });
        indexN = octavelist.findIndex(item=> item.nameoctave ===  this.state.name);
         this.setState({
        records : octavelist[indexN].listoctave,
        });
        this.randomSound();
        })
        .catch((err) => {
        console.log(err.message, err.code);
        console.log('has notes no counter');
         imageN = Math.floor(Math.random() * this.state.logbook.length);
        this.setState({
        name : this.state.logbook[imageN],
        maxCount : 5,
        records : octavelist[imageN].listoctave,
        });
        indexN = octavelist.findIndex(item=> item.nameoctave ===  this.state.name);
         this.setState({
        records : octavelist[indexN].listoctave,
        });
        this.randomSound();
        });
    }
    else {
         RNFS.readFile(path1, 'ascii')
            .then((res) => {
              console.log('no notes has counter');
             imageN = Math.floor(Math.random() * octavelist.length);
             indexN = imageN;
             this.setState({
             name : octavelist[indexN].nameoctave,
             records : octavelist[indexN].listoctave,
            maxCount : res,
             });
              this.randomSound();
         })
         .catch(() => {
         // console.log(err.message, err.code);
          console.log('no notes no counter');
          imageN = Math.floor(Math.random() * octavelist.length);
          indexN = imageN;
          this.setState({
          name : octavelist[indexN].nameoctave,
          records : octavelist[indexN].listoctave,
          maxCount : 5,
          });
            this.randomSound();
       });
    }
  } catch (error) {
    // Error retrieving data
  }
};

  render() {
    return (
      <View style={styles.container}>
       <ImageBackground
          source={require('../media/img/background.jpg')}
          style={styles.imagebackground}>

         {/* Play Sound */}
         <Modal transparent={true} visible={this.state.showMusic} animationType="slide">
         <View style={styles.modalbackground}>
         <View style={{alignItems:'center', alignContent:'center', marginTop : Dimensions.get('window').width * 0.15}}>
              <Image  style={{height:100, width:100,backgroundColor:'white',
              borderRadius: 10,
              borderColor: 'black',
              borderWidth: 5}} source={require('../media/img/hear.gif')}/>
              </View>
          </View>
        </Modal>

 {/* Modal Quit the Scale*/}
         <Modal transparent={true} visible={this.state.showQuit} animationType="slide">
         <View style={styles.modalbackground}>
          <View style={styles.viewmodalQ}>
              <Text style={styles.textquit}>Quit?</Text>
              <View
              style={styles.viewmodalQQ}>
               <TouchableOpacity style={styles.buttonyes}
                 onPress={() => this.backAction()}>
                <Text style={styles.textqq}>YES</Text>
              </TouchableOpacity>
              <TouchableOpacity style={styles.buttonno}
              onPress={() => this.setState({showQuit: false})}>
                <Text style={styles.textqq}>NO</Text>
              </TouchableOpacity>
              </View>
            </View>
          </View>
        </Modal>

        {/* Modal Correct*/}
        <Modal transparent={true} visible={this.state.showC}  animationType="slide">
         <View style={styles.modalbackground}>
          <View style={styles.viewmodalCW}>
          <ImageBackground source={require('../media/img/correctAlert.png')} style={styles.imagecw}>
              <Text style={styles.textcw}>Correct</Text>
              <View style={styles.viewbutton}>
              <TouchableOpacity style={styles.buttonc} onPress={() => this.setState({showC: false})}>
                <Text style={styles.buttonok}>OK</Text>
              </TouchableOpacity>
              </View>
              </ImageBackground>
            </View>
          </View>
        </Modal>

        {/* Modal Wrong*/}
         <Modal transparent={true} visible={this.state.showW} animationType="slide">
         <View style={styles.modalbackground}>
          <View style={styles.viewmodalCW}>
            <ImageBackground source={require('../media/img/wrongAlert.png')} style={styles.imagecw}>
              <Text style={styles.textcw}>Wrong</Text>
               <View style={styles.viewbutton}>
                <TouchableOpacity style={styles.buttonc} onPress={() => this.setState({showW: false})}>
                <Text style={styles.buttonok}>OK</Text>
              </TouchableOpacity>
              </View>
              </ImageBackground>
            </View>
          </View>
        </Modal>

        {/* Modal Done*/}
        <Modal transparent={true} visible={this.state.showDone} animationType="slide">
         <View style={styles.modalbackground}>
          <View style={styles.viewmodalD}>
            <ImageBackground source={require('../media/img/doneAlert.png')} style={styles.imagedone}>
              <Text style={styles.textwelldone}>Well Done</Text>
              <Text style={styles.modaltextcorrect}>Correct : {this.state.correct}</Text>
              <Text style={styles.modaltextwrong}>Wrong: {this.state.wrong}</Text>
              <View
              style={styles.viewmodalDD}>
              <TouchableOpacity style={styles.buttonc} onPress={() => this.backAction()}>
                <Text style={styles.buttonok}>OK</Text>
              </TouchableOpacity>
              </View>
              </ImageBackground>
            </View>
          </View>
        </Modal>

        <StatusBar hidden />
        <View style={styles.c1}>
          <View style={styles.cc1}>
          <Text style={styles.wrong}>{this.state.wrong}</Text>
            <Text style={styles.correct}>{this.state.correct} / {this.state.maxCount}</Text>
              <Stopwatch
            secs
            start={this.state.start}
            getTime={(tt) => {
              //console.log(tt);
              stime = tt;
            }}
            // Options for the styling
            options={{//timer
                      container: {
                        backgroundColor: 'black',
                        padding: 5,
                        borderRadius: 10,
                        borderColor:'white',
                        borderWidth:3,
                        width: 200,
                        alignItems: 'center',
                      },
                      text: {
                        fontSize: 25,
                        color: '#FFF',
                        textAlign: 'center',
                        paddingTop: 5,
                        alignItems: 'center',
                        fontFamily: 'sans-serif',
                      }}}/>
          </View>
          <View>
            <View style={styles.submit}>
              <Button
                title="  PLAY  "
                color="#E07EF9"
                onPress={this.playButton}
              />
            </View>
          </View>
        </View>
      <View style={{borderWidth:5, borderColor:'black'}}/>
         <ScrollView
            horizontal={true}
            style={{
              flexDirection: 'row',
            }}
            showsHorizontalScrollIndicator={false}>
            {NOTESWHITE.map((item,id) => (
             <TouchableHighlight
              style={
                keywordsList.find((element) => element === item.name)
                   ? styles.selectedKeywordStyle
                  : styles.buttonStyle
              }
              onPress={() => this.toggleKeyword(item.name)}
              key={id}>
              <Text style={styles.textStyle}> {item.name} </Text>

            </TouchableHighlight>
            ))}
            {NOTESBLACK.map((item, id) => (
                <TouchableHighlight
              style={
                keywordsList.find((element) => element === item.name)
                  ? [styles.SbuttonB1, {marginLeft: config.deviceWidth * item.left}]
                  : [styles.buttonB1, {marginLeft: config.deviceWidth * item.left}]
              }
              onPress={() => this.toggleKeyword(item.name)}
              key={id}>
              <Text style={styles.textStyleB}>{item.name}</Text>
            </TouchableHighlight>
          ))}
          </ScrollView>
        </ImageBackground>
      </View>
    );
  }
}

export default Listen;
