import React, { useState, useEffect } from "react";
import {
  StyleSheet,
  View,
  StatusBar,
  TextInput,
  Text,
  Switch,
} from "react-native";
import themeColors from '../components/themeColors';
import ImageHeader from "../components/ImageHeader";
import { connect } from 'react-redux';
import { TouchableOpacity } from "react-native-gesture-handler";
import request from '../utility/PromiseRequest';
import { i18n } from '../utility/i18n';


// ---------------------------------------------------------------------------------------------

function SettingsTextInput(props) {
  return (
    <React.Fragment>
      <Text style={settingsGroupStyles.label}>{props.label}</Text>
      <TextInput
        style={settingsGroupStyles.textInput}
        placeholder={props.placeholder}
        placeholderTextColor="rgba(167,167,167,1)"
        selectionColor='rgb(120,120,120)'
        value={props.value}
      ></TextInput>
    </React.Fragment>
  );
}

function SettingsSwitch(props) {
  const [isEnabled, setIsEnabled] = useState(false);
  const toggleSwitch = () => setIsEnabled(previousState => !previousState);

  return (
    <React.Fragment>
      <Text style={settingsGroupStyles.label}>{props.label}</Text>
      <Switch
        value={isEnabled}
        //thumbColor={themeColors["WET ASPHALT"]}
        onValueChange={toggleSwitch}
        trackColor={{ false: "#767577", true: themeColors["NEPHRITIS"] }}
        //thumbColor={isEnabled ? "#f5dd4b" : "#f4f3f4"}
        ios_backgroundColor="grey"
        style={settingsGroupStyles.switch}
      />
    </React.Fragment>
  )
}

function SettingsButton(props) {

  return (
    <React.Fragment>
      <Text style={settingsGroupStyles.label}>{props.label}</Text>
      <TouchableOpacity style={settingsGroupStyles.buttonTouchable} onPress={props.onPress}>
        <Text style={settingsGroupStyles.buttonText}>{props.buttonText}</Text>
      </TouchableOpacity>
    </React.Fragment>
  )

}

function SettingsText(props) {
  return (
    <React.Fragment>
      <Text style={settingsGroupStyles.label}>{props.label}</Text>
      <Text style={settingsGroupStyles.text}>{props.text}</Text>
    </React.Fragment>
  )
}


function SettingsSlider(props) {
  /*
    <Slider
    value={props.value}
    disabled={props.disabled}
    thumbTintColor={themeColors["WET ASPHALT"]}
    minimumTrackTintColor={themeColors["CLOUDS"]}
    maximumTrackTintColor={themeColors["CLOUDS"]}
    style={settingsGroupStyles.slider}
  />
  */

  return (
    <React.Fragment>
      <Text style={settingsGroupStyles.label}>{props.label}</Text>
    </React.Fragment>
  )
}

function SettingsCombo(props) {

}


function SettingsGroup(props) {

  return (
    <View style={settingsGroupStyles.container}>
      <Text style={settingsGroupStyles.title}>{props.title}</Text>
      <View style={settingsGroupStyles.subsettings}>
        {React.Children.map(props.children, (child, idx) =>
          <View style={idx == 0 ? [settingsGroupStyles.row, settingsGroupStyles.firstRow] : settingsGroupStyles.row}>
            {child}
          </View>
        )}
      </View>
    </View>
  );
};

const settingsGroupStyles = StyleSheet.create({
  container: {
    padding: 20,
    paddingRight: 30,
  },
  title: {
    color: "white",
    fontSize: 20,
    fontWeight: "600",
  },
  subsettings: {
    padding: 10,
    paddingLeft: 30,
  },
  row: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    borderTopColor: "rgba(255, 255,255, 0.6)",
    paddingTop: 5,
    paddingBottom: 5,
    borderTopWidth: 0.5,
    minHeight: 40,
  },
  firstRow: {
    paddingTop: 0,
    borderTopWidth: 0,
  },
  label: {
    color: "white",
    fontSize: 17,
  },
  textInput: {
    color: "rgba(255,255,255,1)",
    marginTop: 8,
    textAlign: "right",
  },
  slider: {
    minWidth: 100,
    width: 150,
    //minHeight: 50,
  },
  switch: {
    //minHeight: 50,
    //minWidth: 80,
  },
  buttonText: {
    color: "rgba(255,255,255,1)",
    width: "100%",
    textAlign: "center",
  },
  text : {
    color: "rgba(255,255,255,1)",
    width: "100%",
    textAlign: "right",
  },
  buttonTouchable: {
    backgroundColor: themeColors["CARROT"],
    width: 128,
    padding: 10,
    justifyContent: "center",
    borderRadius: 4,
  }
});

// ---------------------------------------------------------------------------------------------


async function queryDeviceFirmwareVersion(swimTrackerHost) {
  const result = await request({ url: "http://" + swimTrackerHost + "/api/status", responseType: "json" });
  return result["firmware"]["version"];
}

async function queryNewestFirmwareVersion() {
  const QUERY_URL = "https://swimtracker-update.bauer.tech/VERSION";
  const result = await request({ url: QUERY_URL, responseType: "text" });
  console.log("newest firmware version, got", result);
  return result;
}


function SettingsView(props) {

  const [deviceFirmwareVersion, setDeviceFirmwareVersion] = useState("");
  const [newestFirmwareVersion, setNewestFirmwareVersion] = useState("");

  useEffect(() => {
    Promise.all([queryDeviceFirmwareVersion(props.settings.swimTrackerHost), queryNewestFirmwareVersion()]).then(
      (values) => {
        setDeviceFirmwareVersion(values[0]);
        setNewestFirmwareVersion(values[1]);
      }
    );
  });

  const doFirmwareUpdate = () => {
    request({ url: "http://" + props.settings.swimTrackerHost + "/api/firmwareupdate", responseType: "text"});
  };

  return (
    <View style={{ flex: 1 }}>
      <StatusBar barStyle="light-content" backgroundColor="rgba(0,0,0,0.4)" translucent={true} />
      <View style={{ flex: 1 }}>
        <ImageHeader
          text={i18n.t('settings').toUpperCase()}
          navigation={props.navigation}
          image={require("../assets/infinity_pool2.jpg")}
        />

        <View style={{ flex: 1, backgroundColor: themeColors["BELIZE HOLE"] }}>
          <SettingsGroup title="swimtracker Device">
            <SettingsTextInput
              label="URL/IP"
              placeholder="swimtracker-????"
              value={props.settings.swimTrackerHost}
            />
            <SettingsSwitch label="Start automatically" />
            <SettingsSwitch label="Stop automatically" />
            <SettingsButton label="Tare" buttonText="GO" onPress={props.device.conn.sendTareCommand} />
            <SettingsButton label="WiFi config" buttonText="Reset" onPress={props.device.conn.wifiResetToProvisioning} />
            <SettingsText label="Firmware version" text={deviceFirmwareVersion}></SettingsText>
            <SettingsText label="Newest Firmware" text={newestFirmwareVersion}></SettingsText>
            <SettingsButton label="Update Firmware" buttonText="GO" onPress={doFirmwareUpdate}></SettingsButton>
          </SettingsGroup>
        </View>
      </View>
    </View>
  )
}

const mapStateToProps = (state) => {
  return { settings: state.settings };
};

export default connect(mapStateToProps)(SettingsView);
