package com.Tricot.calcutator.data;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.Tricot.calcutator.And_Application;
import com.Tricot.calcutator.Calculator2pager.Calculator2.Calcul2_10pager;
import com.Tricot.calcutator.Calculator2pager.Calculator2.Calcul2_1pager;
import com.Tricot.calcutator.Calculator2pager.Calculator2.Calcul2_2pager;
import com.Tricot.calcutator.Calculator2pager.Calculator2.Calcul2_3pager;
import com.Tricot.calcutator.Calculator2pager.Calculator2.Calcul2_4pager;
import com.Tricot.calcutator.Calculator2pager.Calculator2.Calcul2_5pager;
import com.Tricot.calcutator.Calculator2pager.Calculator2.Calcul2_6pager;
import com.Tricot.calcutator.Calculator2pager.Calculator2.Calcul2_7pager;
import com.Tricot.calcutator.Calculator2pager.Calculator2.Calcul2_8pager;
import com.Tricot.calcutator.Calculator2pager.Calculator2.Calcul2_9pager;
import com.Tricot.calcutator.CalculatorMenu.Bar_select;
import com.Tricot.calcutator.R;

import java.text.DecimalFormat;
import java.util.ArrayList;

public class Calculation2_pager extends AppCompatActivity implements OnTimePickerSerListener{
    public static Context mContext;
    int cal2_1;
    ViewPager pager;
    public Integer pageNum;
    Integer pages;
    Integer bars;
    boolean barmaker;
    boolean barmk;
    EditText yard;
    EditText count;
    EditText weight;
    EditText yarnweights;
    EditText one;
    EditText beamMeter;
    EditText inners;
    EditText meterss;
    double change_num;
    int ym_switch;
    Double conversion_ym;
    EditText cal2_1_mil;
    EditText[] cal2_1_rackmm;
    EditText[] cal2_1_lenght;
    String formattedStringPrice;
    String formattedStringPrice1;
    String formattedStringPrice2;
    String strColor="#434F69";

    final DecimalFormat myFormatter= new DecimalFormat("###,###");
    @Override
    public void onTimePickerSet(int cal1_1s, int cal1_3s, int cal1_4s) { }

    public void onbarMakerSet(int cal2_1s){
        cal2_1 = cal2_1s;
    }

    class MoviePagerAdapter extends FragmentStatePagerAdapter {
        ArrayList<Fragment> items = new ArrayList<Fragment>();

        public MoviePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        public void addItem(Fragment item){
            items.add(item);
        }

        @Override
        public Fragment getItem(int position) {
            return items.get(position);
        }

        @Override
        public int getCount() {
            pageNum = pager.getCurrentItem();
            return items.size();
        }
    }
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calculator_pager2);
        mContext = this;
        final RadioGroup R_group=(RadioGroup)findViewById(R.id.Bar_Group);
        Intent intent = getIntent();
        pages = intent.getExtras().getInt("pages");
        bars= intent.getExtras().getInt("bars");
        barmaker = intent.getExtras().getBoolean("barmaker");

        ym_switch=((And_Application)this.getApplication()).getYm_switch();

        if(ym_switch==0){
            change_num=((And_Application)this.getApplication()).getConversion_ym();
        }else{
            change_num=((And_Application)this.getApplication()).getConversion_my();
        }


        //페이지들 연결
        pager = findViewById(R.id.calcul2vp);
        pager.setOffscreenPageLimit(15);

        MoviePagerAdapter adapter = new MoviePagerAdapter(getSupportFragmentManager());

        Calcul2_1pager fragment2_1 = new Calcul2_1pager();
        adapter.addItem(fragment2_1);

        Calcul2_2pager fragment2_2 = new Calcul2_2pager();
        adapter.addItem(fragment2_2);

        Calcul2_3pager fragment2_3 = new Calcul2_3pager();
        adapter.addItem(fragment2_3);

        Calcul2_4pager fragment2_4 = new Calcul2_4pager();
        adapter.addItem(fragment2_4);

        Calcul2_5pager fragment2_5 = new Calcul2_5pager();
        adapter.addItem(fragment2_5);

        Calcul2_6pager fragment2_6 = new Calcul2_6pager();
        adapter.addItem(fragment2_6);

        Calcul2_7pager fragment2_7 = new Calcul2_7pager();
        adapter.addItem(fragment2_7);

        Calcul2_8pager fragment2_8 = new Calcul2_8pager();
        adapter.addItem(fragment2_8);

        Calcul2_9pager fragment2_9 = new Calcul2_9pager();
        adapter.addItem(fragment2_9);

        Calcul2_10pager fragment2_10 = new Calcul2_10pager();
        adapter.addItem(fragment2_10);

        pager.setAdapter(adapter);

        pagemove();

        pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
        {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
            {
            }

            @Override
            public void onPageSelected(int position)
            {
                if(position==0){
                    if(cal2_1==0){
                        Intent intent = new Intent(getApplicationContext(), Bar_select.class);
                        intent.putExtra("menu",2);
                        intent.putExtra("pages",position);
                        startActivity(intent);
                        finish();
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state)
            {
            }
        });
    }



    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        savedInstanceState.putAll(savedInstanceState);
    }

    //페이지 컨트롤러

    public void pagemove(){
        if(pages!=null){
            barmk=false;
            pager.setCurrentItem(pages,true);
        }

    }
    public void calculation(View v) {
        if (pageNum == 0) {
            try{
                for(int i=1; i<=bars; i++){
                    EditText mils = findViewById(100+i);
                    EditText rackmms = findViewById(200+i);
                    TextView length = findViewById(300+i);
                    Float mil = Float.parseFloat(mils.getText().toString());
                    Float rackmm = Float.parseFloat(rackmms.getText().toString());
                    float calcul1 = (float) (mil*91.44/480*rackmm/1000);
                    float calculround1 = (float) (Math.round(calcul1*100)/100.0);
                    length.setTextSize(18);
                    length.setTextColor(Color.parseColor(strColor));
                    length.setTypeface(null, Typeface.BOLD);
                    length.setText(calculround1+"m/y");
                }
            }catch (NumberFormatException e){
            }
        }
        if (pageNum == 1) {
            yard = findViewById(R.id.weaving_yard);
            EditText width = findViewById(R.id.weaving_width);
            EditText length = findViewById(R.id.weaving_length);
            EditText loss = findViewById(R.id.weaving_loss);
            TextView total_length=findViewById(R.id.beam_total_length);
            try{
                float weaving_yard = Float.parseFloat(yard.getText().toString());
                float weaving_width = Float.parseFloat(width.getText().toString());
                float weaving_length = Float.parseFloat(length.getText().toString());
                float weaving_loss=Float.parseFloat(loss.getText().toString());

                double calcul = weaving_yard/weaving_width*weaving_length;
                double calculround = calcul*(100+weaving_loss)/100;
                long calculround2 = Math.round(calculround);
                formattedStringPrice=myFormatter.format(calculround2);
                total_length.setText(formattedStringPrice + "m");
            }catch (NumberFormatException e){
                Toast.makeText(this.getApplicationContext(),"값을 제대로 입력해 주세요", Toast.LENGTH_LONG).show();
            }
        }
        if (pageNum == 2) {
            count=findViewById(R.id.bon_default);
            EditText in=findViewById(R.id.bon_in);
            EditText out=findViewById(R.id.bon_out);
            TextView real=findViewById(R.id.bon_real_count);

            try{
                float bon_default=Integer.parseInt(count.getText().toString());
                float bon_in=Integer.parseInt(in.getText().toString());
                float bon_out=Integer.parseInt(out.getText().toString());

                double calcul=bon_default/(bon_in+bon_out)*bon_in;
                double calculround = Math.round(calcul*10)/10.0;


                real.setText(calculround+"본");

            }catch (NumberFormatException e){
                Toast.makeText(this.getApplicationContext(),"값을 제대로 입력해 주세요", Toast.LENGTH_LONG).show();
            }
        }
        if (pageNum == 3) {
            weight = findViewById(R.id.totalyarn_weight1);

        }
        if (pageNum == 4) {
            weight = findViewById(R.id.yarnlength_length1);


        }
        if (pageNum == 5) {
            yarnweights = findViewById(R.id.yarnWeight_1);

        }
        if (pageNum == 6) {
            beamMeter = findViewById(R.id.beamMeter);
            EditText beamInnerdiameter = findViewById(R.id.beamInnerdiameter);
            EditText beamOuterdiameter = findViewById(R.id.beamOuterdiameter);
            TextView beamSpeed = findViewById(R.id.beamSpeed);

            try{
                float beammeter = Float.parseFloat(beamMeter.getText().toString());
                float beaminnerdiameter = Float.parseFloat(beamInnerdiameter.getText().toString());
                float beamouterdiameter = Float.parseFloat(beamOuterdiameter.getText().toString());
                double calcul = beammeter*2000;
                double calculround = calcul/(beaminnerdiameter+beamouterdiameter);
                int calculroundint = (int)calculround;
                formattedStringPrice=myFormatter.format(calculroundint);
                beamSpeed.setText(formattedStringPrice+"WDG");
            }catch (NumberFormatException e){
                Toast.makeText(this.getApplicationContext(),"값을 제대로 입력해 주세요", Toast.LENGTH_LONG).show();
            }
        }
        if (pageNum == 7) {
            one = findViewById(R.id.BeamSpeed);
            EditText two = findViewById(R.id.Beam_inner);
            EditText three = findViewById(R.id.Beam_outer);
            TextView result = findViewById(R.id.Yarn_length);
            try{
                float Beam_speed = Float.parseFloat(one.getText().toString());
                float Beam_inner = Float.parseFloat(two.getText().toString());
                float Beam_outer = Float.parseFloat(three.getText().toString());
                double calcul =Beam_inner+Beam_outer;
                double calculround = calcul*Beam_speed/2000;
                double calculround1 = Math.round(calculround);
                int calculround1int =(int)calculround1;
                formattedStringPrice=myFormatter.format(calculround1int);
                result.setText(formattedStringPrice + "m");
            }catch (NumberFormatException e){
                Toast.makeText(this.getApplicationContext(),"값을 제대로 입력해 주세요", Toast.LENGTH_LONG).show();
            }
        }
        if (pageNum == 8) {
            inners = findViewById(R.id.inner_1);
            EditText outers = findViewById(R.id.outer_1);
            EditText turnss = findViewById(R.id.turns);
            EditText inners1 = findViewById(R.id.inner_2);
            EditText outers1 = findViewById(R.id.outer_2);
            TextView beamdata = findViewById(R.id.beamData);
            TextView beamturn = findViewById(R.id.beamTurn);

            try{
                float inner = Float.parseFloat(inners.getText().toString());
                float outer = Float.parseFloat(outers.getText().toString());
                float turns = Float.parseFloat(turnss.getText().toString());
                float inner1 = Float.parseFloat(inners1.getText().toString());
                float outer1 = Float.parseFloat(outers1.getText().toString());

                /* 계산 */
                double calcul1 = (float)(outer1-inner1)*turns/(outer-inner);
                double calcul2 = (float)(outer1+inner1)/2*calcul1/1000;

                /* 반올림 */
                double calculround1 = Math.round(calcul1);
                double calculround2 = Math.round(calcul2);

                /* 소수점을 지우기 위한 형변환 */
                int calculch = (int)calculround1;
                int calculch2 = (int)calculround2;
                formattedStringPrice1=myFormatter.format(calculch);
                formattedStringPrice2=myFormatter.format(calculch2);
                beamturn.setText(formattedStringPrice1 + "WDG");
                beamdata.setText(formattedStringPrice2 + "meter");
            }catch (NumberFormatException e){
                Toast.makeText(this.getApplicationContext(),"값을 제대로 입력해 주세요", Toast.LENGTH_LONG).show();
            }
        }
        if (pageNum == 9) {
            meterss = findViewById(R.id.beam_meters);
            EditText deniars = findViewById(R.id.beam_deniar);
            EditText bons = findViewById(R.id.beam_bon);
            EditText beamcounts = findViewById(R.id.beam_count);
            TextView beamweight = findViewById(R.id.beam_weight);
            TextView totalweight = findViewById(R.id.beam_total_count);

            try{
                float meters = Float.parseFloat(meterss.getText().toString());
                float deniar = Float.parseFloat(deniars.getText().toString());
                float bon = Float.parseFloat(bons.getText().toString());
                float beamcount = Float.parseFloat(beamcounts.getText().toString());

                double calcul1 = meters*bon/9000*deniar/1000;
                double calcul2 = beamcount*calcul1;
                double calculround1 = Math.round(calcul1*10)/10.0;
                double calculround2 = Math.round(calcul2*10)/10.0;
                formattedStringPrice1=myFormatter.format(calculround1);
                formattedStringPrice2=myFormatter.format(calculround2);
                beamweight.setText(calculround1+"kg");
                totalweight.setText(calculround2+"kg");
            }catch (NumberFormatException e){
                Toast.makeText(this.getApplicationContext(),"값을 제대로 입력해 주세요", Toast.LENGTH_LONG).show();
            }
        }

    }
    /*
    public void capture(View v){
        cknums=cknums+1;
        try {
            View view = findViewById(R.id.captures_1);
            view.buildDrawingCache();
            // 긴 화면도 가져오기 위한 함수 호출

            Bitmap bitmap = loadBitmapFromView(view);

            if(cknums>=2 && bitmap!=null) {
                // 저장 하기 위한 함수 호출
                screenshot(bitmap);
                cknums=0;
                Toast.makeText(this.getApplicationContext(),"저장되었습니다",Toast.LENGTH_SHORT).show();
            }else if(cknums==1) {
                //수정필요
                Toast.makeText(this.getApplicationContext(),"다시 한번 눌러주세요",Toast.LENGTH_SHORT).show();
            }
        }catch (IllegalArgumentException e) {
            e.printStackTrace();
            Toast mToast= Toast.makeText(this.getApplicationContext(),"사진저장에실패하셨습니다",Toast.LENGTH_SHORT);
            mToast.show();
        }

    }
    public static Bitmap loadBitmapFromView(View v){
        Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        v.layout(-725, 0, 1800, v.getLayoutParams().height);
        v.draw(c);
        return b;
    }
    public void screenshot(Bitmap bm){
        String extr = Environment.getExternalStorageDirectory().toString();
        File mFolder = new File(extr + "/TexCalculator");
        // 해당 폴더가 없으면 생성
        if (!mFolder.exists()) {
            mFolder.mkdir();
        }
        Random random = new Random();
        String s = "TexCalculator_" + String.valueOf( random.nextInt(99999)) + ".png";
        File file = new File(mFolder.getAbsolutePath(), s);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    */
}
