package com.example.todoapi;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@Controller
public class TweetController {

    @Autowired
    private TweetRepository repository;

    // 画像を保存するフォルダ（※ご自身の環境に合わせて調整が必要かもしれません）
    // とりあえず今回はプロジェクト直下の "uploads" フォルダに保存する設定にします
    private static final String UPLOAD_DIR = System.getProperty("user.dir") + "/src/main/resources/static/images/";

    // 1. タイムライン画面を表示する
    @GetMapping("/timeline")
    public String showTimeline(Model model) {
        // データベースから全てのつぶやきを取得
        List<Tweet> tweets = repository.findAll();
        // 画面（HTML）に渡す
        model.addAttribute("tweets", tweets);
        return "timeline"; // timeline.htmlを表示する
    }

    // 2. つぶやきを投稿する（画像 + テキスト）
    @PostMapping("/timeline")
    public String postTweet(@RequestParam("name") String name,
                            @RequestParam("content") String content,
                            @RequestParam("image") MultipartFile file) throws IOException {
        
        // --- ここから：画像の保存処理（昨日の復習！） ---
        String fileName = file.getOriginalFilename();
        // ファイルが空でない場合のみ保存処理を行う
        if (fileName != null && !fileName.isEmpty()) {
            File dest = new File(UPLOAD_DIR + fileName);
            file.transferTo(dest); // ファイルをフォルダに保存
        }
        // --- ここまで ---

        // データベースに保存するデータを作成
        Tweet tweet = new Tweet();
        tweet.setName(name);      // 名前
        tweet.setContent(content);// 内容
        tweet.setImgName(fileName);// 画像のファイル名だけをDBに保存
        tweet.setTweetDate(LocalDateTime.now()); // 現在時刻

        // DBに保存
        repository.save(tweet);

        // 完了したらタイムライン画面に戻る
        return "redirect:/timeline";
    }
}