/* eslint-disable prettier/prettier */
/* eslint-disable react-native/no-inline-styles */
/* eslint-disable prettier/prettier */
import React from 'react';
import {
  SafeAreaView,
  ImageBackground,
  Text,
  View,
  Image,
  ScrollView,
  BackHandler,
  Pressable,
} from 'react-native';
import styles from '../style/styleSettings';
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';
import notesData from './dataNotes';
var path1 = RNFS.DocumentDirectoryPath + '/counter.txt';
var counter = 0;
var notes = notesData;


export default class SettingsScale 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);
      });
  };

  _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('../media/img/background.jpg')}
          style={styles.imagebackground}>
          <SafeAreaView>
          <View style={styles.view1}>
          <Text style={styles.textques}>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={styles.scroll}>
              <View
                style={styles.view2}>
                {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={styles.image}/>
                      <Text style={styles.textname}>
                        {item.name}
                      </Text>
                    </Pressable>
                  </View>
                ))}
              </View>
            </ScrollView>
          </SafeAreaView>
          </ImageBackground>
      </View>
    );
  }
}
