/* eslint-disable prettier/prettier */
/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {
  SafeAreaView,
  ImageBackground,
  Text,
  View,
  //TouchableOpacity,
  StyleSheet,
  Image,
  ScrollView,
  Dimensions,
 // TextInput,
 BackHandler,
 Pressable,
} from 'react-native';
import Orientation from 'react-native-orientation';
import Notes from './data';
import * as RNFS from 'react-native-fs';
import NumericInput from 'react-native-numeric-input';
import AsyncStorage from '@react-native-async-storage/async-storage';

//var path = RNFS.DocumentDirectoryPath + '/settings.txt';
var path1 = RNFS.DocumentDirectoryPath + '/counter.txt';


const config = {
  deviceWidth: Dimensions.get('window').width,
  deviceHeight: Dimensions.get('window').height,
};
var counter = 0;
/* eslint-disable prettier/prettier */
const notes = [
   'C Major',
   'D Major','E Major',
   'F Sharp Major',
   'F Major',
   'E Flat Major',
   'D Flat Major',
   'G Major',
   'A Major',
   'B Major',
   'C Sharp Major',
   'B Flat Major',
   'A Flat Major',
   'G Flat Major',
   'Bass Clef C Major',
   'Bass Clef D Major',
   'Bass Clef E Major',
   'Bass Clef F Sharp Major',
   'Bass Clef F Major',
   'Bass Clef E Flat Major',
   'Bass Clef D Flat Major',
   'Bass Clef G Major',
   'Bass Clef A Major',
   'Bass Clef B Major',
   'Bass Clef C Sharp Major',
   'Bass Clef B Flat Major',
   'Bass Clef A Flat Major',
   'Bass Clef G Flat Major',
];

export default class Settings extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
      value: 0,
      listN : [],
    };
  }
  toggleKeyword = (keyword) => {
  // console.log(notes.indexOf(keyword));
    let list = notes;
    let index = -1;
    if ((index = notes.indexOf(keyword)) !== -1) {
      list.splice(index, 1);
    } else {
         list.push(keyword);
    }
    this.setState({listN: list});
    if (this.state.listN !== null){
       this.setState({listN: list});
         this.saveData(this.state.listN);
    }
    else {
          this.setState({listN: notes});
         this.saveData2(this.state.listN);
    }

    this._retrieveData();
   // console.log(notes);
  };

    saveData = async () => {
    AsyncStorage.setItem('@notes_key', JSON.stringify(this.state.listN), (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);
      });
  };

   saveData = async () => {
    AsyncStorage.setItem('@notes_key', JSON.stringify(this.state.listN), (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);
      });
  };

  _retrieveData = async () => {
  try {
    const value = await AsyncStorage.getItem('@notes_key');
    if (value !== null) {
      // We have data!!
      console.log(value);
    }
  } catch (error) {
    // Error retrieving data
  }
};


      saveData1 = async () => {
      RNFS.writeFile(path1,JSON.stringify(counter),'utf8',)
        .then((success) => {
        //console.log(JSON.stringify(counter));
        })
        .catch((err) => {
          console.log(err.message);
        });
  };

    displayData1 = async () => {
    RNFS.readFile(path1, 'ascii')
      .then((res) => {
        console.log(JSON.stringify(res));
      })
      .catch((err) => {
        console.log(err.message, err.code);
      });
  };

    componentWillUnmount() {
     Orientation.lockToPortrait();
     BackHandler.removeEventListener('hardwareBackPress', this.homeExit);
    // Orientation.lockAsync(Orientation.OrientationLock.PORTRAIT_UP);
  }

  componentDidMount() {
   // notes.splice(0, notes.length);
   // console.log(notes);
    Orientation.lockToPortrait();
        BackHandler.addEventListener('hardwareBackPress', this.homeExit);
   // console.log(notes.length);
    counter = 0;
    RNFS.unlink(path1).then(res => {
    console.log('delete');
    RNFS.scanFile(path1);
})
.catch(err => {
    console.log(err.message, err.code);
});
  }

    onChange(number, type) {
    //console.log(number, type); // 1, + or -
    counter = number;
    if (counter > 0) {
    this.saveData1(counter);
    console.log(number);
    this.displayData1();
  }
  }

    homeExit = async () => {
    this.props.navigation.navigate('1');

    //Orientation.lockToPortrait();
  };

  render() {
    return (
      <View style={styles.container}>
      <ImageBackground
          source={require('../img/background.jpg')}
          style={{
            width: '100%',
            height: '100%',
          }}>
          <SafeAreaView>
          <View style={{alignItems:'center',marginTop: '15%',  marginLeft: config.deviceWidth * 0.08,
                  marginRight: config.deviceWidth * 0.1, flexDirection: 'row',
                  flexWrap: 'wrap'}}>
                  <Text style={{fontSize: 16,marginRight:9}}>No. of Questions :  </Text>
          <NumericInput
            value={this.state.value}
            minValue={0}
            maxValue={100}
            onChange={this.onChange.bind(this)}
            onLimitReached={(isMax,msg) => console.log(isMax,msg)}
            totalWidth={150}
            totalHeight={40}
            iconSize={25}
            step={1}
            valueType="real"
            rounded
            textColor="black"
            iconStyle={{ color: 'white' }}
            rightButtonBackgroundColor="black"
            leftButtonBackgroundColor="black"/>
            </View>
            <ScrollView style={{marginTop: '5%'}}>
              <View
                style={{
                  flexDirection: 'row',
                  flexWrap: 'wrap',
                  width: config.deviceWidth,
                  marginLeft: config.deviceWidth * 0.08,
                  marginRight: config.deviceWidth * 0.1,
                  marginBottom: config.deviceHeight * 0.12,
                }}>
                {Notes.map((item, id) => (
                  <View key={id}>
                    <Pressable
                      style={
                        notes.find((element) => element === item.name)
                          ? styles.selectedKeywordStyle
                          : styles.buttonStyle
                      }
                      onPress={() => this.toggleKeyword(item.name)}
                      key={id}>
                      <Image
                        source={item.image}
                        style={{
                          width: 100,
                          height: 100,
                        }}
                      />
                      <Text style={{textAlign: 'center', paddingBottom: 10}}>
                        {item.name}
                      </Text>
                    </Pressable>
                  </View>
                ))}
              </View>
            </ScrollView>
          </SafeAreaView>
          </ImageBackground>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    justifyContent: 'center',
    width: '100%',
    height: '100%',
  },
  buttonStyle: {
    flex: 1,
    width: config.deviceWidth * 0.4,
    alignItems: 'center',
    borderWidth: 3,
    borderColor: 'white',
    borderRadius: 10,
    backgroundColor: 'rgba(52, 52, 52, 0.0)',
    opacity:0.4,
    padding: 10,
    marginRight: config.deviceWidth * 0.03,
    marginBottom: config.deviceHeight * 0.03,
  },
  selectedKeywordStyle: {
    flex: 1,
    width: config.deviceWidth * 0.4,
    alignItems: 'center',
    borderWidth: 3,
    borderColor: 'black',
     backgroundColor: 'white',
   // backgroundColor: 'rgba(0,0,0,0)',
    borderRadius: 10,
    marginRight: config.deviceWidth * 0.03,
    marginBottom: config.deviceHeight * 0.03,
    padding: 10,
  },
});
