package net.micode.myapplication.service;

import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import net.micode.myapplication.model.Chapter;
import net.micode.myapplication.model.Course;
import net.micode.myapplication.repository.CourseRepository;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class CourseOutlineImporter {
    private static final String TAG = "CourseOutlineImporter";
    private CourseRepository courseRepository;
    private Gson gson;
    
    public CourseOutlineImporter(CourseRepository courseRepository) {
        this.courseRepository = courseRepository;
        this.gson = new Gson();
    }
    
    /**
     * 从assets文件夹导入课程大纲
     */
    public boolean importCourseOutlineFromAssets(Context context, String fileName) {
        try {
            InputStream inputStream = context.getAssets().open(fileName);
            return importCourseOutline(inputStream);
        } catch (IOException e) {
            Log.e(TAG, "无法读取assets文件: " + fileName, e);
            return false;
        }
    }
    
    /**
     * 从输入流导入课程大纲
     */
    public boolean importCourseOutline(InputStream inputStream) {
        try {
            JsonObject jsonObject = JsonParser.parseReader(new InputStreamReader(inputStream)).getAsJsonObject();
            return parseAndImportCourseOutline(jsonObject);
        } catch (Exception e) {
            Log.e(TAG, "解析JSON失败", e);
            return false;
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                Log.e(TAG, "关闭输入流失败", e);
            }
        }
    }
    
    /**
     * 解析并导入课程大纲
     */
    private boolean parseAndImportCourseOutline(JsonObject jsonObject) {
        try {
            // 解析课程基本信息
            Course course = parseCourseInfo(jsonObject);
            if (course == null) {
                Log.e(TAG, "解析课程信息失败");
                return false;
            }
            
            // 解析章节信息
            List<Chapter> chapters = parseChapters(jsonObject, course.getCourseId());
            if (chapters.isEmpty()) {
                Log.w(TAG, "没有找到章节信息");
            }
            
            // 导入到数据库
            return importToDatabase(course, chapters);
            
        } catch (Exception e) {
            Log.e(TAG, "解析课程大纲失败", e);
            return false;
        }
    }
    
    /**
     * 解析课程基本信息
     */
    private Course parseCourseInfo(JsonObject jsonObject) {
        try {
            String courseId = getStringValue(jsonObject, "id");
            String title = getStringValue(jsonObject, "title");
            
            if (courseId == null || title == null) {
                Log.e(TAG, "课程ID或标题为空");
                return null;
            }
            
            Course course = new Course();
            course.setCourseId(courseId);
            course.setCourseName(title);
            
            // 可选字段
            String school = getStringValue(jsonObject, "school");
            if (school != null) {
                course.setSchool(school);
            }
            
            return course;
            
        } catch (Exception e) {
            Log.e(TAG, "解析课程基本信息失败", e);
            return null;
        }
    }
    
    /**
     * 解析章节信息
     */
    private List<Chapter> parseChapters(JsonObject jsonObject, String courseId) {
        List<Chapter> chapters = new ArrayList<>();
        
        try {
            JsonArray nodes = jsonObject.getAsJsonArray("nodes");
            if (nodes == null) {
                Log.w(TAG, "没有找到nodes数组");
                return chapters;
            }
            
            int chapterNumber = 1;
            for (JsonElement element : nodes) {
                if (element.isJsonObject()) {
                    JsonObject chapterObj = element.getAsJsonObject();
                    Chapter chapter = parseChapter(chapterObj, courseId, chapterNumber);
                    if (chapter != null) {
                        chapters.add(chapter);
                        chapterNumber++;
                    }
                }
            }
            
        } catch (Exception e) {
            Log.e(TAG, "解析章节信息失败", e);
        }
        
        return chapters;
    }
    
    /**
     * 解析单个章节
     */
    private Chapter parseChapter(JsonObject chapterObj, String courseId, int chapterNumber) {
        try {
            String chapterId = getStringValue(chapterObj, "id");
            String chapterTitle = getStringValue(chapterObj, "title");
            
            if (chapterId == null || chapterTitle == null) {
                Log.w(TAG, "章节ID或标题为空");
                return null;
            }
            
            Chapter chapter = new Chapter();
            chapter.setChapterId(chapterId);
            chapter.setCourseId(courseId);
            chapter.setChapterNumber(chapterNumber);
            chapter.setChapterTitle(chapterTitle);
            
            // 解析关键词
            List<String> keywords = parseKeywords(chapterObj);
            for (String keyword : keywords) {
                chapter.addKeyword(keyword);
            }
            
            // 解析别名
            List<String> aliases = parseAliases(chapterObj);
            for (String alias : aliases) {
                chapter.addAlias(alias);
            }
            
            return chapter;
            
        } catch (Exception e) {
            Log.e(TAG, "解析单个章节失败", e);
            return null;
        }
    }
    
    /**
     * 解析关键词
     */
    private List<String> parseKeywords(JsonObject obj) {
        List<String> keywords = new ArrayList<>();
        
        try {
            JsonArray keywordsArray = obj.getAsJsonArray("keywords");
            if (keywordsArray != null) {
                for (JsonElement element : keywordsArray) {
                    if (element.isJsonPrimitive()) {
                        keywords.add(element.getAsString());
                    }
                }
            }
        } catch (Exception e) {
            Log.w(TAG, "解析关键词失败", e);
        }
        
        return keywords;
    }
    
    /**
     * 解析别名
     */
    private List<String> parseAliases(JsonObject obj) {
        List<String> aliases = new ArrayList<>();
        
        try {
            JsonArray aliasesArray = obj.getAsJsonArray("aliases");
            if (aliasesArray != null) {
                for (JsonElement element : aliasesArray) {
                    if (element.isJsonPrimitive()) {
                        aliases.add(element.getAsString());
                    }
                }
            }
        } catch (Exception e) {
            Log.w(TAG, "解析别名失败", e);
        }
        
        return aliases;
    }
    
    /**
     * 获取字符串值
     */
    private String getStringValue(JsonObject obj, String key) {
        try {
            JsonElement element = obj.get(key);
            if (element != null && element.isJsonPrimitive()) {
                return element.getAsString();
            }
        } catch (Exception e) {
            Log.w(TAG, "获取字符串值失败: " + key, e);
        }
        return null;
    }
    
    /**
     * 导入到数据库
     */
    private boolean importToDatabase(Course course, List<Chapter> chapters) {
        try {
            // 检查课程是否已存在
            Course existingCourse = courseRepository.getCourseById(course.getCourseId());
            if (existingCourse != null) {
                Log.i(TAG, "课程已存在，将更新数据: " + course.getCourseId());
                // 可以选择更新或跳过
            }
            
            // 批量插入课程和章节
            courseRepository.insertCourseWithChapters(course, chapters);
            boolean success = true; // 方法没有返回值，假设成功
            
            if (success) {
                Log.i(TAG, String.format("成功导入课程: %s (%d 个章节)", 
                    course.getCourseName(), chapters.size()));
            } else {
                Log.e(TAG, "导入课程失败");
            }
            
            return success;
            
        } catch (Exception e) {
            Log.e(TAG, "导入到数据库失败", e);
            return false;
        }
    }
    
    /**
     * 批量导入多个课程大纲
     */
    public boolean importMultipleCourseOutlines(Context context, List<String> fileNames) {
        boolean allSuccess = true;
        int successCount = 0;
        
        for (String fileName : fileNames) {
            boolean success = importCourseOutlineFromAssets(context, fileName);
            if (success) {
                successCount++;
            } else {
                allSuccess = false;
                Log.e(TAG, "导入失败: " + fileName);
            }
        }
        
        Log.i(TAG, String.format("批量导入完成: %d/%d 成功", successCount, fileNames.size()));
        return allSuccess;
    }
    
    /**
     * 获取导入状态信息
     */
    public String getImportStatusMessage(boolean success, String fileName) {
        if (success) {
            return String.format("成功导入课程大纲: %s", fileName);
        } else {
            return String.format("导入失败: %s", fileName);
        }
    }
}