import React, { Component } from 'react';
import {
  Text,
  View,
  StyleSheet,
  Dimensions,
} from 'react-native';
import Carousel from 'react-native-looped-carousel';
import Modal from 'react-native-modalbox';
import RNFetchBlob from 'react-native-fetch-blob';
import Toast from 'react-native-simple-toast';
import * as Progress from 'react-native-progress';
import { unzip } from 'react-native-zip-archive';
import RNFS from 'react-native-fs';

import AsyncStorageHelper from '../../../utils/AsyncStorageHelper';

const randomColor = require('randomcolor'); // import the script

const DIR = RNFetchBlob.fs.dirs;
const LEETCODE_PATH = '/growth-leetcode-api-master';
const LeetCodeUrl = 'https://github.com/phodal/growth-leetcode-api/archive/master.zip';
const { width, height } = Dimensions.get('window');
const styles = StyleSheet.create({
  wrapper: {
    paddingTop: 50,
    flex: 1,
  },
  text: {
    paddingBottom: 50,
  },
  modal: {
    justifyContent: 'center',
    alignItems: 'center',
    height: 300,
    width: 300,
  },
});

function getRandomColor() {
  return randomColor({
    luminosity: 'light',
    hue: 'random',
  });
}

export default class LeetCodeView extends Component {
  static componentName = 'LeetCodeView';
  static modal = null;

  static unzipFiles(res) {
    unzip(res.path(), `${DIR.DocumentDir}`).then(() => {
      AsyncStorageHelper.set('leetcode.unzip', 'true');
    }).catch((err) => {
      console.log(`解压失败 ${err}`);
      Toast.show(`解压失败 ${err}`);
    });
  }

  constructor(props) {
    super(props);

    this.state = {
      progress: 0.001,
      questions: null,
      size: { width, height },
      hasDownloaded: false,
    };
  }

  componentWillMount() {
    AsyncStorageHelper.get('leetcode.index', (err, result) => {
      let index = 0;
      if (result !== null) {
        index = parseInt(result, 10);
      }

      this.setState({
        index,
      });
    });

    AsyncStorageHelper.get('leetcode.downloaded', (err, result) => {
      if (result === 'true') {
        this.setState({
          hasDownloaded: true,
        });
      }
    });
  }

  componentDidMount() {
    const that = this;
    AsyncStorageHelper.get('leetcode.downloaded', (err, result) => {
      if (result !== 'true') {
        this.modal.open();
        this.fetchFile(LeetCodeUrl, 'leetcode');
      } else {
        AsyncStorageHelper.get('leetcode.questions', (error, questions) => {
          if (questions) {
            that.setState({
              questions: JSON.parse(questions),
            });
          } else {
            that.loadQuestionsToDB();
          }
        });
      }
    });
  }

  onLayoutDidChange = (e) => {
    const layout = e.nativeEvent.layout;
    this.setState({ size: { width: layout.width, height: layout.height } });
  };

  loadQuestionsToDB() {
    const leetCodeDir = DIR.DocumentDir.concat(`${LEETCODE_PATH}/api.json`);
    console.log(leetCodeDir);

    RNFS.readFile(leetCodeDir, 'utf8')
    .then((json) => {
      this.setState({
        questions: JSON.parse(json),
      });

      AsyncStorageHelper.set('leetcode.questions', json);
    }).catch((error) => {
      Toast.show(error);
      AsyncStorageHelper.set('leetcode.downloaded', 'false');
    });
  }

  fetchFile(url, fileName) {
    RNFetchBlob
    .config({
      path: `${DIR.DocumentDir}/${fileName}.zip`,
    })
    .fetch('GET', url, {})
    .progress((received, total) => {
      const progressWithoutRound = received / total;

      let progress = Math.round(progressWithoutRound * 1e2) / 1e2;
      if (progress > 1) {
        progress = 1;
      }
      this.setState({ progress });
    })
    .then((res) => {
      const now = new Date();
      console.log(`${now} 下载成功`);
      console.log(res.path());

      LeetCodeView.unzipFiles(res);
      this.loadQuestionsToDB();

      AsyncStorageHelper.set('leetcode.downloaded', 'true');
      this.setState({ hasDownloaded: true });
    })
    .catch((err) => {
      Toast.show(`下载失败 ${err}`);
    });
  }

  render() {
    const hasDownloaded = this.state.hasDownloaded;
    const questions = this.state.questions;

    if (!hasDownloaded || !questions) {
      return (
        <Modal
          style={[styles.modal]}
          position={'center'}
          ref={(modal) => { this.modal = modal; }}
        >
          <Text style={styles.text}>正在为您下载</Text>
          <Progress.Circle
            style={styles.progress}
            progress={this.state.progress}
            indeterminate
            size={80}
          />
        </Modal>
      );
    }

    return (
      <View style={{ flex: 1 }} onLayout={this.onLayoutDidChange}>
        <Carousel
          delay={2000}
          style={this.state.size}
          autoplay={false}
          pageInfo={false}
          onAnimateNextPage={p => console.log(p)}
        >
          <View style={[{ backgroundColor: getRandomColor() }, this.state.size]}>
            <Text>1</Text>
          </View>
          <View style={[{ backgroundColor: getRandomColor() }, this.state.size]}>
            <Text>2</Text>
          </View>
          <View style={[{ backgroundColor: getRandomColor() }, this.state.size]}>
            <Text>3</Text>
          </View>
        </Carousel>
      </View>
    );
  }
}

@@ -1265,252 +1265,8 @@
 l;%0A%0A
-  static unzipFiles(res) %7B%0A    unzip(res.path(), %60$%7BDIR.DocumentDir%7D%60).then(() =%3E %7B%0A      AsyncStorageHelper.set('leetcode.unzip', 'true');%0A    %7D).catch((err) =%3E %7B%0A      console.log(%60%E8%A7%A3%E5%8E%8B%E5%A4%B1%E8%B4%A5 $%7Berr%7D%60);%0A      Toast.show(%60%E8%A7%A3%E5%8E%8B%E5%A4%B1%E8%B4%A5 $%7Berr%7D%60);%0A    %7D);%0A  %7D%0A%0A
   co
@@ -3529,28 +3529,20 @@
 %0A%0A      
-LeetCodeView
+this
 .unzipFi
@@ -3554,40 +3554,8 @@
 es);
-%0A      this.loadQuestionsToDB();
 %0A%0A  
@@ -3680,32 +3680,32 @@
 atch((err) =%3E %7B%0A
-
       Toast.show
@@ -3734,16 +3734,285 @@
 );%0A  %7D%0A%0A
+  unzipFiles(res) %7B%0A    unzip(res.path(), %60$%7BDIR.DocumentDir%7D%60).then(() =%3E %7B%0A      this.loadQuestionsToDB();%0A      AsyncStorageHelper.set('leetcode.unzip', 'true');%0A    %7D).catch((err) =%3E %7B%0A      console.log(%60%E8%A7%A3%E5%8E%8B%E5%A4%B1%E8%B4%A5 $%7Berr%7D%60);%0A      Toast.show(%60%E8%A7%A3%E5%8E%8B%E5%A4%B1%E8%B4%A5 $%7Berr%7D%60);%0A    %7D);%0A  %7D%0A%0A
   render

fix load db issue