import Axios from 'axios';
import Constants from 'expo-constants';
import { Alert, Linking } from 'react-native';


function compareVersion(v1, v2) {
    if (typeof v1 !== 'string') return false;
    if (typeof v2 !== 'string') return false;
    v1 = v1.split('.');
    v2 = v2.split('.');
    const k = Math.min(v1.length, v2.length);
    for (let i = 0; i < k; ++ i) {
        v1[i] = parseInt(v1[i], 10);
        v2[i] = parseInt(v2[i], 10);
        if (v1[i] > v2[i]) return 1;
        if (v1[i] < v2[i]) return -1;
    }
    return v1.length == v2.length ? 0: (v1.length < v2.length ? -1 : 1);
}


export default function CheckVersion(navigation) {
    let version = Constants.manifest.version

    Axios.get('https://excelso.ravintolavip.com/cms/v2/detail/apps-version').then(respon => {
        let version_server = respon.data.content5
        let msg_res = respon.data.content6
        if (compareVersion(version, version_server) == -1) {

            Alert.alert(
                'Update Version',
                msg_res,
                [
                    {
                        text: 'Nanti',
                        style: 'cancel'
                    },
                    {
                        text: 'Update', onPress: () => {
                            if (Platform.OS === 'ios') {
                                Linking.openURL('https://apps.apple.com/id/app/excelso/id1434669847')
                            } else {
                                Linking.openURL('https://play.google.com/store/apps/details?id=id.web.ravintola.excelsocrm')
                            }
                        }
                    }
                ],
                { cancelable: false }
            );
        }
    }).catch(error => {
        console.log(error)
    })
}