// noPage

import { LibComponent } from 'esoftplay/cache/lib/component/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibTextstyle } from 'esoftplay/cache/lib/textstyle/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';
import { MarketInput_label } from 'esoftplay/cache/market/input_label/import';
import { createTimeout } from 'esoftplay/timeout';

import React from 'react';
import { Platform, Text, TextInput, View } from 'react-native';

export interface MarketInput_squareProps {
  label?: string,
  placeholder?: string,
  mask?: string,
  maskFrom?: 'start' | 'end',
  prefix?: string,
  suffix?: string,
  error?: boolean,
  allowFontScaling?: boolean,
  autoCapitalize?: "none" | "sentences" | "words" | "characters",
  autoCorrect?: boolean,
  autoFocus?: boolean,
  blurOnSubmit?: boolean,
  onBlur?: () => void,
  onFocus?: () => void,
  caretHidden?: boolean,
  contextMenuHidden?: boolean,
  defaultValue?: string,
  editable?: boolean,
  inactive?: boolean,
  keyboardType?: "default" | "email-address" | "numeric" | "phone-pad",
  maxLength?: number,
  multiline?: boolean,
  onSubmitEditing?: () => void,
  onChangeText?: (text: string, maskedText?: string) => void,
  placeholderTextColor?: string,
  returnKeyType?: "done" | "go" | "next" | "search" | "send",
  secureTextEntry?: boolean,
  selectTextOnFocus?: boolean,
  selectionColor?: string,
  style?: any,
  containerStyle?: any,
  value?: string,
  mandatory?: boolean,
  mandatoryColor?: string,
  testID?: string
}

export interface LibInputState {
  hasFocus: boolean,
  error?: string,
  helper?: string
}
export default class m extends LibComponent<MarketInput_squareProps, LibInputState> {
  text: string
  ref: any
  constructor(props: MarketInput_squareProps) {
    super(props);
    this.state = { hasFocus: false }
    this.text = ''
    this.ref = React.createRef()
    this.getText = this.getText.bind(this);
    this.mask = this.mask.bind(this);
    this.unmask = this.unmask.bind(this);
    this.setError = this.setError.bind(this);
    this.clearError = this.clearError.bind(this);
    this.setHelper = this.setHelper.bind(this);
    this.clearHelper = this.clearHelper.bind(this);
    this.getTextMasked = this.getTextMasked.bind(this);
  }

  getText(): string {
    return this.unmask(this.text)
  }

  getTextMasked(): string {
    return this.text
  }

  focus(): void {
    this.ref.focus()
  }

  blur(): void {
    this.ref.blur()
  }

  setHelper(msg: string): void {
    this.setState({ helper: msg })
  }

  clearHelper(): void {
    this.setState({ helper: undefined })
  }

  setError(msg: string): void {
    this.setState({ error: msg })
  }

  clearError(): void {
    this.setState({ error: undefined })
  }

  reverseString(str: string): string {
    let out = '';
    for (let i = str.length - 1; i >= 0; i--) {
      out += str[i];
    }
    return out;
  }

  mask(text: string): string {
    let { mask, maskFrom } = this.props
    if (mask) {
      if (!maskFrom) maskFrom = 'start'
      let rMask = mask
      let rText = this.unmask(text)
      if (maskFrom == 'end') {
        rMask = this.reverseString(mask)
        rText = this.reverseString(rText)
      }
      let maskedText = ''
      let _addRange = 0
      let _addMaskChar = ''
      for (let i = 0; i < rMask.length; i++) {
        const iMask = rMask[i];
        if (iMask == '#') {
          if (rText?.[i - _addRange] != undefined) {
            maskedText += _addMaskChar + rText[i - _addRange]
          }
          else {
            break
          }
          _addMaskChar = ''
        }
        else {
          _addMaskChar += iMask
          _addRange++
        }
      }
      if (maskFrom == 'end') {
        maskedText = this.reverseString(maskedText)
      }
      this.ref.setNativeProps({ text: maskedText })
      return maskedText
    }
    return text
  }

  unmask(text: string): string {
    let _text = text
    let { mask } = this.props
    if (mask) {
      let masks = mask.match(/((?!\#).)/g)
      if (masks) {
        for (let i = 0; i < masks.length; i++) {
          _text = _text?.replace?.(new RegExp(LibUtils.escapeRegExp(masks[i]), 'g'), '')
        }
      }
      return _text
    }
    return _text
  }

  setText(text: string): void {
    if (this.ref) {
      this.ref.setNativeProps({ text: this.mask(text) })
      this.text = this.mask(text)
      this.clearError()
    }
  }

  componentDidUpdate(prevProps: MarketInput_squareProps, prevState: LibInputState): void {
    if (this.ref) {
      this.ref.setNativeProps({ text: this.mask(this.text) })
    }
  }

  componentDidMount(): void {
    super.componentDidMount()
    const timeout = createTimeout()
    timeout.set(() => {
      if (this.props.defaultValue) {
        this.setText(this.props.defaultValue)
      }
      timeout.clear()
    }, 300);
  }

  render(): any {
    const { error } = this.state
    return (
      <>
        <View style={{ paddingHorizontal: 17, marginTop: 4, marginBottom: 8, ...this.props.containerStyle }} >
          {this.props.label && <MarketInput_label label={this.props.label} mandatory={this.props.mandatory} mandatoryColor={this.props.mandatoryColor} />}
          <View testID={this.props?.testID || 'input_square'} style={{ flexDirection: "row", alignItems: "center", borderWidth: 1, borderRadius: 6, borderColor: this.props.error ? LibStyle.colorRed : "#ddd", backgroundColor: this.props.inactive ? "#eee" : "white", paddingHorizontal: 10 }} >
            {this.props.prefix && <LibTextstyle textStyle="callout" text={this.props.prefix} style={{ fontSize: 14, color: "#aaa" }} />}
            <TextInput
              ref={(r) => this.ref = r}
              placeholder={this.props.placeholder}
              placeholderTextColor='#c5c5c5'
              maxLength={this.props.mask ? this.props.mask.length : undefined}
              allowFontScaling={false}
              {...this.props}
              onChangeText={(e) => {
                this.text = this.mask(e)
                if (error != undefined)
                  this.clearError()
                if (this.props.onChangeText) this.props.onChangeText(this.unmask(e), e)
              }}
              style={[{ minHeight: 40, flex: 1, paddingVertical: Platform.OS == 'ios' ? 10 : 4, fontSize: 14, color: error ? "#e44545" : "#000", }, this.props.style]}
            />
            {this.props.suffix && <LibTextstyle textStyle="callout" text={"    " + this.props.suffix} style={{ fontSize: 14, color: "#aaa" }} />}
          </View>
        </View>
        {
          error &&
          <View style={{ flex: 1, marginHorizontal: 8, marginTop: 4 }} >
            <Text style={{ fontSize: 8, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#e44545" }} >{error}</Text>
          </View>
        }
      </>
    )
  }
}