package chaoran.business.engine.impl;

/*
 **********************************************
 *      DATE           PERSON       REASON
 *    2021-02-18          FXY        Created
 **********************************************
 */


import android.content.Context;
import android.content.SharedPreferences;
import android.webkit.JavascriptInterface;

import chaoran.business.activity.MainActivity;
import chaoran.business.engine.SettingEngine;
import chaoran.business.engine.entity.NetworkSetting;
import chaoran.business.engine.entity.Setting;
import com.google.gson.Gson;

/**
 * 网络设置引擎
 */
public class NetworkSettingEngine implements SettingEngine {

    private Context context;

    private Gson gson;

    public NetworkSettingEngine(Context context) {
        this.context = context;
        gson = new Gson();
    }

    //展示网络设置
    @Override
    public Setting getSetting() {
        SharedPreferences spf = context.getSharedPreferences("crtech", Context.MODE_PRIVATE);
        Integer port = spf.getInt("port", -1);
        Integer screen_rotation = spf.getInt("screen_rotation", 3);
        String address = spf.getString("address", "").replaceAll(" ", "");
        String path = spf.getString("path", "").replaceAll(" ", "");
        NetworkSetting networkSetting = new NetworkSetting();
        networkSetting.setAddress(address);
        networkSetting.setPort(port);
        networkSetting.setPath(path);
        networkSetting.setScreen_rotation(screen_rotation);
        networkSetting.setHide_bar(spf.getInt("hide_bar", 0));
        return networkSetting;
    }

    @Override
    public boolean saveSetting(Setting setting) {
        NetworkSetting networkSetting = (NetworkSetting) setting;
        SharedPreferences.Editor editor = context.getSharedPreferences("crtech", Context.MODE_PRIVATE).edit();
        editor.putString("address", networkSetting.getAddress());
        editor.putString("path", networkSetting.getPath());
        editor.putInt("port", networkSetting.getPort());
        editor.putInt("screen_rotation", networkSetting.getScreen_rotation());
        editor.putInt("hide_bar", networkSetting.getHide_bar());
        editor.commit();
        MainActivity.SCREEN_ROTATION = networkSetting.getScreen_rotation();
        MainActivity.hideBar = networkSetting.getHide_bar();
//        MainActivity.startDirection = networkSetting.getStart_direction();
        return true;
    }

    /**
     * 页面显示设置
     *
     * @return
     */
    @JavascriptInterface
    public String getStringSetting() {
        return gson.toJson(getSetting());
    }

    /**
     * 页面保存设置
     *
     * @param s
     * @return
     */
    @JavascriptInterface
    public boolean saveSetting(String s) {
        return saveSetting(gson.fromJson(s, NetworkSetting.class));
    }
}
