import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import moment from 'moment';
import { environment } from 'src/environments/environment';

@Injectable({
  providedIn: 'root'
})
export class FeedService {
  private apiUrl = environment.apiUrl;
  private authToken = environment.authToken;

  constructor(private http: HttpClient) {}

  fetchPosts(isTeam: boolean, showAll: boolean): Observable<any[]> {
    const url = `${this.apiUrl}?isweb=true&isteam=${isTeam}&showall=${showAll}`;
    return this.http.get<string[]>(url, {
      headers: {
        'Authorization': this.authToken,
        'Content-Type': 'application/json'
      }
    }).pipe(
      map(results => {
        let rank = 0;
        return results.map(result => {
          let title = '';
          const strs = result.includes('===') ? result.split('===') : result.split('==');
          
          if (strs.length > 1) {
            const content = strs[1].trim();
            if (content.startsWith('Round')) {
              title = `第 ${content.replace('Round', '').trim()} 回合`;
            } else if (content.startsWith('终局审判')) {
              title = '终局审判';
            } else if (content.startsWith('排名')) {
              title = '排名';
            } else if (content.startsWith('伤害排行榜')) {
              title = '伤害排行榜';
            } else if (content.startsWith('空投')) {
              title = '空投';
            } else if (content.startsWith('技术得分排行榜')) {
              title = '技术得分排行榜';
            } else if (content.startsWith('本场比赛最佳角色')) {
              title = '本场比赛最佳角色';
            } else if (content.startsWith('团队模式随机分组')) {
              title = '团队模式随机分组';
            } else if (content.startsWith('角色')) {
              rank++;
              title = `第 ${rank} 名：${content.replace('角色', '').trim()}`;
            }
          } else if (strs.length > 3) {
            title = `${strs[1].trim()} ${strs[3].replace('角色', '').trim()}`;
          }

          return {
            author: 'FunGame 模拟',
            title: title || '',
            date: moment().format('YYYY-MM-DD HH:mm:ss'),
            content: result,
            likes: 999,
            forwards: 999,
            comments: 233
          };
        });
      }),
      catchError(error => {
        console.error('Fetch error:', error);
        return throwError(() => new Error('Failed to fetch posts'));
      })
    );
  }
}
