import LoginApi from '../api/LoginApi';
import {proxyServer,channelKey,channelKeys} from '../const/app';
import {localStore} from 'mutants-microfx';
import tools from '../util/tools';
const emptyChannel = {
  throughProxy: false,
  targetURL: 'http://t.chanjet.com/tplus/',
}

const userHttpDomain = ['https://t.chanjet.com','https://xjhwt.chanjet.com'];

export default class Channel {

  targetURL:string;
  throughProxy:boolean;

  static filterURL(targetURL){
    return targetURL;
  }

  constructor(targetURL){
    this.targetURL = Channel.filterURL(targetURL);
    if(targetURL.indexOf(proxyServer) > -1){
      this.throughProxy = true;
    }else{
      this.throughProxy = false;
    }
  }

  static async getChannel(){
    const targetURL = await LoginApi.getTargetURL();
    let channel = new Channel(targetURL);
    channel.cache();
    return channel;
  }

  static setChannel(targetURL){
    let channel = new Channel(targetURL);
    channel.cache();
    return channel;
  }

  //缓存数据
  cache(){
    localStore.set(channelKey,this);
    channelKeys.forEach((channelKey)=>{
      if(!tools.isNull(this[channelKey])){
        localStore.set(channelKey,this[channelKey]);
      }
    });
  }

  static cache(obj){
    localStore.set(channelKey,obj);
    channelKeys.forEach((channelKey)=>{
      if(!tools.isNull(this[channelKey])){
        localStore.set(channelKey,this[channelKey]);
      }
    });
  }

  //恢复数据
  static restore(){
    // let channel =  localStore.get(channelKey);
    // if(channel == null || channel == undefined){
    //   channel = emptyChannel;
    // }
    // return channel;

    const targetURL = localStore.get('targetURL');
    if(!tools.isNull(targetURL)){
      let cacheObj = {};
      channelKeys.forEach((key)=>{
        cacheObj[key] = localStore.get(key);
      });
      return cacheObj; 
    }
    return emptyChannel;
  }

  //清空数据
  static clear(){
    localStore.remove(channelKey);
    channelKeys.forEach((key)=>{
      localStore.remove(key);
    });
  }
}