File size: 6,381 Bytes
cc2caf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250

// Updated storage utility with additional functions

// Type for storing watch history and progress
export interface WatchProgress {
  currentTime: number;
  duration: number;
  lastPlayed: string;
  completed: boolean;
}

// Type for my list items
export interface MyListItem {
  title: string;
  type: 'movie' | 'tvshow';
  addedAt: string;
  posterPath?: string;
  backdropPath?: string;
}

/**
 * Save video watch progress
 */
export const saveVideoProgress = (
  type: 'movie' | 'tvshow',
  title: string,
  seasonEpisode: string | null,
  progress: WatchProgress
): void => {
  try {
    // Create a unique identifier for the content
    const id = seasonEpisode ? `${type}-${title}-${seasonEpisode}` : `${type}-${title}`;
    
    // Get existing watch history
    const historyStr = localStorage.getItem('watch-history') || '{}';
    const history = JSON.parse(historyStr);
    
    // Update the history with new progress
    history[id] = { 
      ...progress, 
      title,
      type,
      seasonEpisode,
      updatedAt: new Date().toISOString() 
    };
    
    // Save back to localStorage
    localStorage.setItem('watch-history', JSON.stringify(history));
  } catch (error) {
    console.error('Failed to save video progress:', error);
  }
};

/**
 * Get video watch progress
 */
export const getVideoProgress = (
  type: 'movie' | 'tvshow',
  title: string,
  seasonEpisode: string | null
): WatchProgress | null => {
  try {
    // Create a unique identifier for the content
    const id = seasonEpisode ? `${type}-${title}-${seasonEpisode}` : `${type}-${title}`;
    
    // Get existing watch history
    const historyStr = localStorage.getItem('watch-history') || '{}';
    const history = JSON.parse(historyStr);
    
    // Return the progress if it exists
    return history[id] || null;
  } catch (error) {
    console.error('Failed to get video progress:', error);
    return null;
  }
};

/**
 * Get watch history
 */
export const getWatchHistory = (limit: number = 0): Array<any> => {
  try {
    // Get existing watch history
    const historyStr = localStorage.getItem('watch-history') || '{}';
    const history = JSON.parse(historyStr);
    
    // Convert object to array and sort by updatedAt (most recent first)
    const historyArray = Object.values(history).sort((a: any, b: any) => {
      return new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime();
    });
    
    // Return all or limited number of items
    return limit > 0 ? historyArray.slice(0, limit) : historyArray;
  } catch (error) {
    console.error('Failed to get watch history:', error);
    return [];
  }
};

/**
 * Clear watch history
 */
export const clearWatchHistory = (): void => {
  try {
    localStorage.removeItem('watch-history');
  } catch (error) {
    console.error('Failed to clear watch history:', error);
  }
};

/**
 * Add item to My List
 */
export const addToMyList = (item: MyListItem): void => {
  try {
    // Get existing my list
    const myListStr = localStorage.getItem('my-list') || '[]';
    const myList = JSON.parse(myListStr);
    
    // Check if item already exists
    const exists = myList.some((listItem: MyListItem) => 
      listItem.title === item.title && listItem.type === item.type
    );
    
    // Add item if it doesn't exist
    if (!exists) {
      myList.push({
        ...item,
        addedAt: new Date().toISOString()
      });
      
      // Save back to localStorage
      localStorage.setItem('my-list', JSON.stringify(myList));
    }
  } catch (error) {
    console.error('Failed to add item to My List:', error);
  }
};

/**
 * Remove item from My List
 */
export const removeFromMyList = (title: string, type: 'movie' | 'tvshow'): void => {
  try {
    // Get existing my list
    const myListStr = localStorage.getItem('my-list') || '[]';
    const myList = JSON.parse(myListStr);
    
    // Filter out the item
    const newList = myList.filter((item: MyListItem) => 
      !(item.title === title && item.type === type)
    );
    
    // Save back to localStorage
    localStorage.setItem('my-list', JSON.stringify(newList));
  } catch (error) {
    console.error('Failed to remove item from My List:', error);
  }
};

/**
 * Check if item is in My List
 */
export const isInMyList = (title: string, type: 'movie' | 'tvshow'): boolean => {
  try {
    // Get existing my list
    const myListStr = localStorage.getItem('my-list') || '[]';
    const myList = JSON.parse(myListStr);
    
    // Check if item exists
    return myList.some((item: MyListItem) => 
      item.title === title && item.type === type
    );
  } catch (error) {
    console.error('Failed to check if item is in My List:', error);
    return false;
  }
};

/**
 * Get all items from My List
 */
export const getAllFromMyList = (): Array<MyListItem> => {
  try {
    // Get existing my list
    const myListStr = localStorage.getItem('my-list') || '[]';
    return JSON.parse(myListStr);
  } catch (error) {
    console.error('Failed to get My List:', error);
    return [];
  }
};

/**
 * Clear My List
 */
export const clearMyList = (): void => {
  try {
    localStorage.removeItem('my-list');
  } catch (error) {
    console.error('Failed to clear My List:', error);
  }
};

// Example of a function that could be replaced with a database implementation
// This can be swapped out with a DB implementation later
export const storageService = {
  // Video progress functions
  saveVideoProgress,
  getVideoProgress,
  getWatchHistory,
  clearWatchHistory,
  
  // My list functions
  addToMyList,
  removeFromMyList,
  isInMyList,
  getAllFromMyList,
  clearMyList,
  
  // Generic storage functions that could be replaced
  setItem: (key: string, value: any): void => {
    try {
      localStorage.setItem(key, JSON.stringify(value));
    } catch (error) {
      console.error(`Failed to store ${key}:`, error);
    }
  },
  
  getItem: <T>(key: string, defaultValue: T): T => {
    try {
      const item = localStorage.getItem(key);
      return item ? JSON.parse(item) : defaultValue;
    } catch (error) {
      console.error(`Failed to retrieve ${key}:`, error);
      return defaultValue;
    }
  },
  
  removeItem: (key: string): void => {
    try {
      localStorage.removeItem(key);
    } catch (error) {
      console.error(`Failed to remove ${key}:`, error);
    }
  }
};

export default storageService;