package com.example.fuckyou;

import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import android.content.Context;

public class MainActivity extends AppCompatActivity {
    public static List<Lesson> kebiaodata=new ArrayList<>();
    public static String getWeekdayFromSunday(String sundayStr, int weekdayNumber) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");

        // 將字串轉成 Date
        Date sundayDate = sdf.parse(sundayStr);

        // 設定 Calendar 為這個週日
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(sundayDate);

        // 計算需要加幾天（1 = 星期一, ..., 7 = 星期日）
        int daysToAdd = weekdayNumber % 7; // 若是 7 (星期日)，則加 0 天
        calendar.add(Calendar.DATE, daysToAdd);

        // 回傳結果
        return sdf.format(calendar.getTime());
    }

    public static List<String> getSundaysInRange(String startDate, String endDate) {
        List<String> sundays = new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-M-d"); // 修改为无前导零的格式

        try {
            // 将日期字符串转换为 Date 对象
            Date start = dateFormat.parse(startDate);
            Date end = dateFormat.parse(endDate);

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(start);

            // 如果开始日期不是周日，找到下一个周日
            if (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
                calendar.add(Calendar.DAY_OF_MONTH, Calendar.SUNDAY - calendar.get(Calendar.DAY_OF_WEEK));
            }

            // 逐个添加每个周日到列表中
            while (!calendar.getTime().after(end)) {
                sundays.add(dateFormat.format(calendar.getTime()));
                calendar.add(Calendar.WEEK_OF_YEAR, 1); // 每次递增一周
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return sundays;
    }
    private void getCookies(String url) throws IOException, ParseException {
        CookieManager cookieManager = CookieManager.getInstance();
        String cookies = cookieManager.getCookie(url);
        Map<String, String> cookiesMap = new HashMap<>();
        for (String cookie : cookies.split(";")) {
            String[] parts = cookie.trim().split("=", 2);
            if (parts.length == 2) {
                cookiesMap.put(parts[0], parts[1]);
            }
        }
        List<String> order = Arrays.asList(
                "JSESSIONID", "iPlanetDirectoryPro", "SF_cookie_2",
                "RouTe_WAF_E1268C", "PORTAL-TOKEN", "SF_cookie_1",
                "web_m_site", "route"
        );
        Map<String, String> sortedCookies = new LinkedHashMap<>();
        for (String key : order) {
            if (cookiesMap.containsKey(key)) {
                sortedCookies.put(key, cookiesMap.get(key));
            }
        }
        StringBuilder sortedCookieHeader = new StringBuilder();
        for (Map.Entry<String, String> entry : sortedCookies.entrySet()) {
            sortedCookieHeader.append(entry.getKey()).append("=").append(entry.getValue()).append("; ");
        }
        List<String> sundays=getSundaysInRange("2025-2-16", "2025-6-31");
        MyDatabaseHelper db=new MyDatabaseHelper(this);
        db.deleteLesson();
        String nodateUrl = "https://zhlj.whu.edu.cn/mobile/homepageapi/getCurriculumData?date=";
        for(String sunday : sundays) {
            OkHttpClient client = new OkHttpClient();
            String apiUrl=nodateUrl+sunday;
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .addHeader("Cookie", sortedCookieHeader.toString())  // 设置 Cookie
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(() ->
                            Toast.makeText(MainActivity.this, "請求失敗: " + e.getMessage(), Toast.LENGTH_SHORT).show()
                    );
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful() && response.body() != null) {
                        String responseData = response.body().string();
                        displayCurriculumData(responseData,sunday);
                    } else {
                        runOnUiThread(() ->
                                Toast.makeText(MainActivity.this, "請求失敗，狀態碼: " + response.code(), Toast.LENGTH_SHORT).show()
                        );
                    }
                }
            });
        }
    }
    public void displayCurriculumData(String responseData,String date) {
        try {
            JSONObject response = new JSONObject(responseData);
            if (response.getInt("code") == 200) {
                JSONArray data = response.getJSONArray("data");
                for (int i = 0; i < data.length(); i++) {
                    JSONObject dayData = data.getJSONObject(i);
                    int day = dayData.getInt("day");
                    JSONArray curriculumList = dayData.getJSONArray("curriculumList");
                    for (int j = 0; j < curriculumList.length(); j++) {
                        JSONObject curriculum = curriculumList.getJSONObject(j);
                        // 只有當有有效數據時才顯示
                        if (curriculum.has("name") && curriculum.getString("name")!="null") {
                            Lesson temp = new Lesson();
                            String today = getWeekdayFromSunday(date, day);
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
                            Date d = sdf.parse(today);
                            temp.name = curriculum.getString("name");
                            temp.teacher = curriculum.getString("teacher");
                            temp.classroom = curriculum.getString("classroom");
                            temp.fromClass = curriculum.getInt("fromClass");
                            temp.endClass = curriculum.getInt("endClass");
                            temp.day = day;
                            temp.date = d;
                            MyDatabaseHelper db=new MyDatabaseHelper(this);
                            db.insertLesson(temp);
                        }
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        /*
        MyDatabaseHelper db=new MyDatabaseHelper(this);
        File dbFile=db.getMyDatabaseFile();
        if (dbFile.exists())
        {
            boolean deleted = dbFile.delete();
            if (deleted) {
                Log.d("Database", "資料庫文件已刪除");
            } else {
                Log.d("Database", "無法刪除資料庫文件");
            }
        }*/
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        WebView webView = findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return false; // 让 WebView 继续加载
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (url.contains("zhlj.whu.edu.cn")) { // 登录成功后访问的页面
                    try {
                        // 等待 Cookie 更新完成
                        new Handler(Looper.getMainLooper()).postDelayed(() -> {
                            try {
                                getCookies(url);// 获取 cookies
                                webView.setVisibility(View.INVISIBLE);
                            } catch (IOException ex) {
                                ex.printStackTrace();
                            } catch (ParseException e) {
                                throw new RuntimeException(e);
                            }
                        }, 1000);  // 延迟 1 秒获取 cookie，确保 Cookie 已经更新
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });
        String loginUrl = "https://cas.whu.edu.cn/authserver/login?service=https%3A%2F%2Fzhlj.whu.edu.cn%2FcasLogin";
        webView.loadUrl(loginUrl);
    }
    public void onMyButtonClick(View view) {
        Intent intent=new Intent(MainActivity.this,showkebiao.class);
        startActivity(intent);
    }

}