package com.seismic.controller;

import com.seismic.model.SeismicMetadata;
import com.seismic.service.SeismicDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;
import java.io.File;

@RestController
@RequestMapping("/ndy/dz")
public class SeismicDataController {

    @Autowired
    private SeismicDataService seismicDataService;

    @GetMapping("/getSeismicMetadata")
    public ResponseEntity<SeismicMetadata> getMetadata(@RequestParam String fileName) {
        try {
            SeismicMetadata metadata = seismicDataService.getMetadata(fileName);
            return ResponseEntity.ok(metadata);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @GetMapping("/getRemoteSeismicData")
    public ResponseEntity<byte[]> getSeismicData(
            @RequestParam String fileName,
            @RequestHeader(value = HttpHeaders.RANGE, required = false) String rangeHeader) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_TYPE, "application/octet-stream");
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);

            byte[] data;
            if (rangeHeader != null) {
                // 处理范围请求
                List<HttpRange> ranges = HttpRange.parseRanges(rangeHeader);
                data = seismicDataService.getSeismicData(fileName, ranges);
                
                // 设置范围响应头
                HttpRange range = ranges.get(0);
                long fileSize = new File(seismicDataPath + fileName).length();
                long start = range.getRangeStart(fileSize);
                long end = range.getRangeEnd(fileSize);
                headers.add(HttpHeaders.CONTENT_RANGE, "bytes " + start + "-" + end + "/" + fileSize);
                headers.add(HttpHeaders.ACCEPT_RANGES, "bytes");
                
                return ResponseEntity.status(HttpStatus.PARTIAL_CONTENT)
                    .headers(headers)
                    .body(data);
            } else {
                // 返回完整文件
                data = seismicDataService.getSeismicData(fileName, null);
                return ResponseEntity.ok()
                    .headers(headers)
                    .body(data);
            }
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
} 